<template>
  <div class="hotel-edit">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? "编辑酒店" : "新增酒店" }}</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="hotel-form"
      >
        <el-tabs v-model="activeTab">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-form-item label="酒店名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入酒店名称" />
            </el-form-item>
            <el-form-item label="酒店地址" prop="address">
              <el-input
                v-model="formData.address"
                placeholder="请输入酒店地址"
              />
            </el-form-item>
            <el-form-item label="联系人" prop="contact">
              <el-input
                v-model="formData.contact"
                placeholder="请输入联系人姓名"
              />
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入联系电话" />
            </el-form-item>
            <el-form-item label="酒店简介" prop="description">
              <el-input
                v-model="formData.description"
                type="textarea"
                rows="4"
                placeholder="请输入酒店简介"
              />
            </el-form-item>
            <el-form-item label="酒店设施" prop="facilities">
              <el-checkbox-group v-model="formData.facilities">
                <el-checkbox label="wifi">WiFi</el-checkbox>
                <el-checkbox label="parking">停车场</el-checkbox>
                <el-checkbox label="restaurant">餐厅</el-checkbox>
                <el-checkbox label="gym">健身房</el-checkbox>
                <el-checkbox label="swimming">游泳池</el-checkbox>
                <el-checkbox label="meeting">会议室</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <!-- 资质信息 -->
          <el-tab-pane label="资质信息" name="qualification">
            <el-form-item label="营业执照" prop="businessLicense">
              <el-upload
                class="upload-demo"
                action="/api/upload"
                :on-success="handleBusinessLicenseSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
              >
                <el-button type="primary">上传营业执照</el-button>
              </el-upload>
              <el-image
                v-if="formData.businessLicense"
                :src="formData.businessLicense"
                class="preview-image"
              />
            </el-form-item>
            <el-form-item label="卫生许可证" prop="hygieneLicense">
              <el-upload
                class="upload-demo"
                action="/api/upload"
                :on-success="handleHygieneLicenseSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
              >
                <el-button type="primary">上传卫生许可证</el-button>
              </el-upload>
              <el-image
                v-if="formData.hygieneLicense"
                :src="formData.hygieneLicense"
                class="preview-image"
              />
            </el-form-item>
            <el-form-item label="特种行业许可证" prop="specialLicense">
              <el-upload
                class="upload-demo"
                action="/api/upload"
                :on-success="handleSpecialLicenseSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
              >
                <el-button type="primary">上传特种行业许可证</el-button>
              </el-upload>
              <el-image
                v-if="formData.specialLicense"
                :src="formData.specialLicense"
                class="preview-image"
              />
            </el-form-item>
          </el-tab-pane>

          <!-- 图片管理 -->
          <el-tab-pane label="图片管理" name="images">
            <el-form-item label="酒店封面" prop="coverImage">
              <el-upload
                class="upload-demo"
                action="/api/upload"
                :on-success="handleCoverImageSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
              >
                <el-button type="primary">上传封面图片</el-button>
              </el-upload>
              <el-image
                v-if="formData.coverImage"
                :src="formData.coverImage"
                class="preview-image"
              />
            </el-form-item>
            <el-form-item label="酒店图片" prop="images">
              <el-upload
                class="upload-demo"
                action="/api/upload"
                :on-success="handleImagesSuccess"
                :on-error="handleUploadError"
                :before-upload="beforeUpload"
                multiple
              >
                <el-button type="primary">上传酒店图片</el-button>
              </el-upload>
              <div class="image-list">
                <el-image
                  v-for="(image, index) in formData.images"
                  :key="index"
                  :src="image"
                  class="preview-image"
                >
                  <template #error>
                    <el-icon><icon-picture /></el-icon>
                  </template>
                </el-image>
              </div>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>

        <div class="form-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import axios from "@/api/axios";

const route = useRoute();
const router = useRouter();
const formRef = ref(null);
const activeTab = ref("basic");

// 判断是否为编辑模式
const isEdit = computed(() => !!route.params.id);

// 表单数据
const formData = reactive({
  name: "",
  address: "",
  contact: "",
  phone: "",
  description: "",
  facilities: [],
  businessLicense: "",
  hygieneLicense: "",
  specialLicense: "",
  coverImage: "",
  images: [],
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: "请输入酒店名称", trigger: "blur" }],
  address: [{ required: true, message: "请输入酒店地址", trigger: "blur" }],
  contact: [{ required: true, message: "请输入联系人", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  businessLicense: [
    { required: true, message: "请上传营业执照", trigger: "change" },
  ],
  hygieneLicense: [
    { required: true, message: "请上传卫生许可证", trigger: "change" },
  ],
  specialLicense: [
    { required: true, message: "请上传特种行业许可证", trigger: "change" },
  ],
};

// 获取酒店详情
const fetchHotelDetail = async (id) => {
  try {
    const res = await axios.get(`/admin/hotels/${id}`);
    if (res.code === 200) {
      Object.assign(formData, res.data);
    } else {
      // 使用测试数据
      const testData = {
        name: "测试酒店",
        address: "贵港市港北区中山路123号",
        contact: "张经理",
        phone: "13800138000",
        description: "这是一家测试酒店",
        facilities: ["wifi", "parking", "restaurant"],
        businessLicense: "/mock/business-license.jpg",
        hygieneLicense: "/mock/hygiene-license.jpg",
        specialLicense: "/mock/special-license.jpg",
        coverImage: "/mock/hotel-cover.jpg",
        images: ["/mock/hotel-1.jpg", "/mock/hotel-2.jpg"],
      };
      Object.assign(formData, testData);
    }
  } catch (error) {
    console.error("获取酒店详情失败：", error);
    ElMessage.error("获取酒店详情失败，使用测试数据");
    // 使用测试数据
    const testData = {
      name: "测试酒店",
      address: "贵港市港北区中山路123号",
      contact: "张经理",
      phone: "13800138000",
      description: "这是一家测试酒店",
      facilities: ["wifi", "parking", "restaurant"],
      businessLicense: "/mock/business-license.jpg",
      hygieneLicense: "/mock/hygiene-license.jpg",
      specialLicense: "/mock/special-license.jpg",
      coverImage: "/mock/hotel-cover.jpg",
      images: ["/mock/hotel-1.jpg", "/mock/hotel-2.jpg"],
    };
    Object.assign(formData, testData);
  }
};

// 上传相关方法
const beforeUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    ElMessage.error("只能上传图片文件！");
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB！");
    return false;
  }
  return true;
};

const handleBusinessLicenseSuccess = (res) => {
  if (res.code === 200 && res.data && res.data.url) {
    formData.businessLicense = res.data.url;
  } else {
    formData.businessLicense = res.url || "/mock/business-license.jpg";
  }
};

const handleHygieneLicenseSuccess = (res) => {
  if (res.code === 200 && res.data && res.data.url) {
    formData.hygieneLicense = res.data.url;
  } else {
    formData.hygieneLicense = res.url || "/mock/hygiene-license.jpg";
  }
};

const handleSpecialLicenseSuccess = (res) => {
  if (res.code === 200 && res.data && res.data.url) {
    formData.specialLicense = res.data.url;
  } else {
    formData.specialLicense = res.url || "/mock/special-license.jpg";
  }
};

const handleCoverImageSuccess = (res) => {
  if (res.code === 200 && res.data && res.data.url) {
    formData.coverImage = res.data.url;
  } else {
    formData.coverImage = res.url || "/mock/hotel-cover.jpg";
  }
};

const handleImagesSuccess = (res) => {
  const imageUrl = res.code === 200 && res.data && res.data.url ? 
    res.data.url : (res.url || "/mock/hotel-image.jpg");
  formData.images.push(imageUrl);
};

const handleUploadError = () => {
  ElMessage.error("上传失败");
};

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let result;
        if (isEdit.value) {
          result = await axios.put(`/admin/hotels/${route.params.id}`, formData);
        } else {
          result = await axios.post("/admin/hotels", formData);
        }
        
        if (result.code === 200) {
          ElMessage.success("保存成功");
          router.push("/admin/hotels");
        } else {
          ElMessage.error(result.message || "保存失败");
        }
      } catch (error) {
        console.error("保存失败：", error);
        ElMessage.error("保存失败，请稍后重试");
      }
    }
  });
};

// 取消
const handleCancel = () => {
  router.back();
};

// 初始化
if (isEdit.value) {
  fetchHotelDetail(route.params.id);
}
</script>

<style scoped>
.hotel-edit {
  padding: 20px;
}

.hotel-form {
  margin-top: 20px;
}

.preview-image {
  width: 200px;
  height: 200px;
  margin: 10px;
  object-fit: cover;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
}

.form-footer {
  margin-top: 20px;
  text-align: center;
}

.empty-state {
  padding: 40px 0;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}

.mt-4 {
  margin-top: 16px;
}
</style>
